import {
  BACKEND_ERROR_CODE,
  createFlatRequest,
  createRequest,
} from 'src/axios';
import { showErrorMsg } from './shared';
import type { RequestInstanceState } from './type';
import { LocalStorage, Notify } from 'quasar';
import { tokenKey } from 'src/use';
import { useWebStore } from 'src/stores/webStore';

export const request = createFlatRequest<
  App.Service.Response,
  RequestInstanceState
>(
  {
    baseURL: process.env.API,
    headers: {
      apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2',
    },
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = LocalStorage.getItem<Api.TokenInfoVO>(tokenKey);
      if (token) {
        headers.set(token.tokenName, token.tokenValue);
      }

      return config;
    },
    isBackendSuccess(response) {
      // when the backend response code is "0000"(default), it means the request is success
      // to change this logic by yourself, you can modify the `VITE_SERVICE_SUCCESS_CODE` in `.env` file
      return String(response.data.code) === process.env.SUCC_CODE;
    },
    async onBackendFail(response, instance) {
      console.log('instance :>> ', instance);

      function handleLogout() {
        console.log('handleLogout :>> ');
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        request.state.errMsgStack = request.state.errMsgStack.filter(
          (msg) => msg !== response.data.msg,
        );
      }
      // when the backend response code is in `modalLogoutCodes`, it means the user will be logged out by displaying a modal
      const modalLogoutCodes = process.env.LOGOUT_CODES?.split(',') || [];
      if (
        modalLogoutCodes.includes(response.data.code + '') &&
        !request.state.errMsgStack?.includes(response.data.msg)
      ) {
        const webStore = useWebStore();
        request.state.errMsgStack = [
          ...(request.state.errMsgStack || []),
          response.data.msg,
        ];

        // prevent the user from refreshing the page
        window.addEventListener('beforeunload', handleLogout);

        Notify.create({
          message: '未登录，请登录',
          position: 'top',
          type: 'positive',
          onDismiss() {
            logoutAndCleanup();
          },
        });
        webStore.loginDig = true;
        webStore.logout();
        return null;
      }
      return null;
    },
    transformBackendResponse(response) {
      return response.data.data;
    },
    onError(error) {
      // when the request is fail, you can show error message

      let message = error.message;
      let backendErrorCode = '';

      // get backend error message and code
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.msg || message;
        backendErrorCode = error.response?.data?.code + '' || '';
      }

      // the error message is displayed in the modal
      const modalLogoutCodes = process.env.LOGOUT_CODES?.split(',') || [];
      if (modalLogoutCodes.includes(backendErrorCode)) {
        return;
      }
      showErrorMsg(request.state, message);
    },
  },
);

export const demoRequest = createRequest<App.Service.DemoResponse>(
  {
    baseURL: process.env.API,
  },
  {
    async onRequest(config) {
      const { headers } = config;

      // set token
      const token = LocalStorage.getItem<Api.TokenInfoVO>(tokenKey);
      if (token) {
        headers.set(token.tokenName, token.tokenValue);
      }

      return config;
    },
    isBackendSuccess(response) {
      // when the backend response code is "200", it means the request is success
      // you can change this logic by yourself
      return response.data.status === '200';
    },
    async onBackendFail(_response) {
      console.log('_response :>> ', _response);
      // when the backend response code is not "200", it means the request is fail
      // for example: the token is expired, refresh token and retry request
    },
    transformBackendResponse(response) {
      return response.data.result;
    },
    onError(error) {
      // when the request is fail, you can show error message

      let message = error.message;

      // show backend error message
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.message || message;
      }

      Notify.create({
        type: 'negative',
        message: message,
        position: 'top',
        progress: true,
        actions: [{ icon: 'close', color: 'white' }],
      });
    },
  },
);
